package com.cupk.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.cupk.pojo.*;
import com.cupk.service.GradeService;
import com.cupk.service.MatchService;
import com.cupk.service.StudentService;
import com.cupk.service.UserService;
import com.cupk.service.impl.StudentServiceImpl;
import com.cupk.utils.COSUtil;
import com.cupk.utils.ImgUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/grade")
public class GradeController {
    @Autowired
    private GradeService gradeService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;
    @Autowired
    private MatchService matchService;


    @PostMapping("/import")
    public Result<Map<String, List>> imp(@RequestParam Integer matchId, @RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Grade> list = reader.readAll(Grade.class);
        Map<String, List> res = new HashMap<>();
        res.put("student", new ArrayList<>());
        res.put("teacher", new ArrayList<>());
        for (Grade l : list) {
            Integer state = gradeService.transferAwardToInteger(l.getStateName());
            l.setState(state);

            Student stu = studentService.findStudentByStuId(l.getStuIdCard());
            if (stu != null) {
                l.setStuId(stu.getId());
            } else {
                res.get("student").add(l.getStuIdCard());
                continue;
            }
            User user = userService.getUserByName(l.getTeacherName());
            if (user != null) {
                l.setTeacherId(user.getId());
            } else {
                res.get("teacher").add(l.getTeacherName());
                continue;
            }
            l.setMatchId(matchId);
            Grade p = gradeService.getGradeByStuAndMatch(stu.getId(), matchId);
            if (p != null) {
                gradeService.updateGrade(l);
            } else {
                System.out.println(l);
                gradeService.addGrade(l);
            }
        }
        return Result.success(res);
    }

    @GetMapping("/export")
    public Result<String> export(@RequestParam Integer matchId) {
        List<Map<String, Object>> grades = gradeService.getListByMatchId(matchId);

        // 创建ExcelWriter（使用Hutool）
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //设置表头
        writer.addHeaderAlias("matchName", "比赛名称");
        writer.addHeaderAlias("matchSession", "比赛届次");
        writer.addHeaderAlias("stateName", "奖项名称");
        writer.addHeaderAlias("updateTime", "录入时间");
        writer.addHeaderAlias("stuName", "姓名");
        writer.addHeaderAlias("stuIdCard", "学号");
        writer.addHeaderAlias("stuCollege", "学院");
        writer.addHeaderAlias("stuGrade", "年级");
        writer.addHeaderAlias("stuMajor", "专业");
        writer.addHeaderAlias("stuClasses", "班级");
        writer.addHeaderAlias("identityCard", "身份证号");
        writer.addHeaderAlias("stuMobile", "手机号");
        writer.addHeaderAlias("teacherName", "指导教师");
        writer.addHeaderAlias("note", "获奖信息备注");

        // 写入数据
        writer.write(grades);

        // 将数据写入到ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        writer.flush(outputStream, true);
        writer.close();

        // 将ByteArrayOutputStream转换为ByteArrayInputStream
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        String download = COSUtil.upLoad(inputStream, ".xlsx", "application/vnd.ms-excel");

        return Result.success(download);
    }

    @GetMapping("/list")
    public Result<List<Map<String, Object>>> list(@RequestParam Integer matchId) {
        Match m = matchService.getMatchById(matchId);
        if (m == null) {
            return Result.error("比赛ID请求非法!");
        }
        List<Map<String, Object>> grades = gradeService.getListByMatchId(matchId);
        return Result.success(grades);
    }

    @GetMapping("/getAward")
    public Result<List<Grade>> getAward(@RequestParam Integer stuId) {
        List<Grade> g = gradeService.getAward(stuId);
        return Result.success(g);
    }
}
